package br.com.peri.validator;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import br.com.peri.entity.PeriEntity;
import br.com.peri.exception.PeriException;

public class PeriValidator implements Serializable {

	private static final long serialVersionUID = 1L;

	private static PeriValidator periValidator;

	public static PeriValidator getInstance() {
		if (periValidator == null) {
			periValidator = new PeriValidator();
		}
		return periValidator;
	}

	private PeriValidator() {
	}

	/**
	 * 
	 * @param <T>
	 * @param object
	 * @return
	 */
	public <T> List<String> getMessagesValidation(T object) {
		Validator validator = Validation.buildDefaultValidatorFactory()
				.getValidator();
		Set<ConstraintViolation<T>> constraintViolations = validator
				.validate(object);
		List<String> msgs = new ArrayList<String>(0);
		for (ConstraintViolation<T> c : constraintViolations) {
			msgs.add(c.getMessage());
		}
		return msgs;
	}

	/**
	 * 
	 * @param <T>
	 * @param object
	 * @throws PeriException
	 */
	public <T extends PeriEntity> void validEntity(T object)
			throws PeriException {
		Validator validator = Validation.buildDefaultValidatorFactory()
				.getValidator();
		Set<ConstraintViolation<T>> constraintViolations = validator
				.validate(object);
		List<String> msgs = new ArrayList<String>(0);
		for (ConstraintViolation<T> c : constraintViolations) {
			msgs.add(c.getMessage());
		}
		if (!msgs.isEmpty()) {
			throw new PeriException(msgs);
		}
	}

}
